package com.example.myblog.controller;

import com.example.myblog.model.Category;
import com.example.myblog.model.TreasureItem;
import com.example.myblog.model.User;
import com.example.myblog.service.CategoryService;
import com.example.myblog.service.TreasureItemService;
import com.example.myblog.service.UserService;
import com.example.myblog.service.SettingsService;
import com.example.myblog.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ContentDisposition;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 百宝箱控制器
 * 处理百宝箱相关的前端展示和后台管理功能
 */
@Controller
public class TreasureController {

    @Autowired
    private TreasureItemService treasureItemService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UserService userService;

    @Autowired
    private SettingsService settingsService;

    @Autowired
    private com.example.myblog.service.OssService ossService;

    // ==================== 前端展示相关 ====================

    /**
     * 显示百宝箱页面
     */
    @GetMapping("/treasure")
    public String showTreasurePage(Model model) {
        // 获取所有启用的项目
        List<TreasureItem> allItems = treasureItemService.getAllEnabledItems();
        List<TreasureItem> websites = treasureItemService.getEnabledItemsByType(TreasureItem.ItemType.WEBSITE);
        List<TreasureItem> files = treasureItemService.getEnabledItemsByType(TreasureItem.ItemType.FILE);

        model.addAttribute("allItems", allItems);
        model.addAttribute("websites", websites);
        model.addAttribute("files", files);
        model.addAttribute("totalCount", treasureItemService.getTotalCount());
        model.addAttribute("websiteCount", treasureItemService.getCountByType(TreasureItem.ItemType.WEBSITE));
        model.addAttribute("fileCount", treasureItemService.getCountByType(TreasureItem.ItemType.FILE));

        // 添加分类信息（用于导航栏）
        model.addAttribute("categories", categoryService.getAllCategories());

        // 背景图设置（与首页保持一致）
        String bg = settingsService.getSettingValueByKey("background_image", "");
        model.addAttribute("backgroundImage", bg);

        // 检查用户权限
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && !auth.getName().equals("anonymousUser")) {
            model.addAttribute("isAdmin", userService.isAdmin(auth.getName()));
        }

        return "treasure";
    }

    /**
     * 搜索百宝箱项目
     */
    @GetMapping("/treasure/search")
    @ResponseBody
    public ResponseEntity<List<TreasureItem>> searchItems(@RequestParam("keyword") String keyword) {
        List<TreasureItem> results = treasureItemService.searchItems(keyword);
        return ResponseEntity.ok(results);
    }

    // ==================== 后台管理相关 ====================

    /**
     * 显示百宝箱管理页面
     */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin/treasure")
    public String showTreasureManagePage(Model model) {
        List<TreasureItem> allItems = treasureItemService.getAllItems();
        List<TreasureItem> websites = treasureItemService.getItemsByType(TreasureItem.ItemType.WEBSITE);
        List<TreasureItem> files = treasureItemService.getItemsByType(TreasureItem.ItemType.FILE);

        model.addAttribute("allItems", allItems);
        model.addAttribute("websites", websites);
        model.addAttribute("files", files);
        model.addAttribute("totalCount", allItems.size());
        model.addAttribute("websiteCount", websites.size());
        model.addAttribute("fileCount", files.size());

        // 添加分类信息（用于导航栏）
        model.addAttribute("categories", categoryService.getAllCategories());

        // 背景图设置（与首页保持一致）
        String bg = settingsService.getSettingValueByKey("background_image", "");
        model.addAttribute("backgroundImage", bg);

        return "admin/treasure";
    }

    /**
     * 添加网站收藏
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/admin/treasure/website")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> addWebsite(
            @RequestParam("displayName") String displayName,
            @RequestParam("url") String url,
            @RequestParam(value = "description", required = false) String description,
            @RequestParam(value = "iconFile", required = false) MultipartFile iconFile) {

        Map<String, Object> response = new HashMap<>();
        
        try {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            User currentUser = userService.getUserByUsername(auth.getName());

            treasureItemService.addWebsiteBookmark(displayName, url, description, iconFile, currentUser.getId());
            
            response.put("success", true);
            response.put("message", "网站收藏添加成功！");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "添加失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 上传文件
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/admin/treasure/file")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "displayName", required = false) String displayName,
            @RequestParam(value = "description", required = false) String description) {

        Map<String, Object> response = new HashMap<>();
        
        try {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            User currentUser = userService.getUserByUsername(auth.getName());

            treasureItemService.uploadFile(file, displayName, description, currentUser.getId());
            
            response.put("success", true);
            response.put("message", "文件上传成功！");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "上传失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 编辑项目
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PutMapping("/admin/treasure/edit/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> editItem(
            @PathVariable Long id,
            @RequestParam("displayName") String displayName,
            @RequestParam(value = "description", required = false) String description,
            @RequestParam(value = "url", required = false) String url) {

        Map<String, Object> response = new HashMap<>();
        
        try {
            treasureItemService.updateItem(id, displayName, description, url);
            response.put("success", true);
            response.put("message", "项目更新成功！");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 删除项目
     */
    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/admin/treasure/delete/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> deleteItem(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            treasureItemService.deleteItem(id);
            response.put("success", true);
            response.put("message", "项目删除成功！");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 切换项目启用状态
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/admin/treasure/toggle/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> toggleItemStatus(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        try {
            TreasureItem item = treasureItemService.toggleItemStatus(id);
            response.put("success", true);
            response.put("enabled", item.getEnabled());
            response.put("message", item.getEnabled() ? "项目已启用" : "项目已禁用");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "操作失败：" + e.getMessage());
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 更新项目排序
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/admin/treasure/reorder")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> reorderItems(@RequestBody List<Long> itemIds) {
        Map<String, Object> response = new HashMap<>();
        try {
            treasureItemService.updateItemsOrder(itemIds);
            response.put("success", true);
            response.put("message", "排序更新成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "排序更新失败：" + e.getMessage());
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 获取项目详情（用于编辑表单）
     */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin/treasure/item/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getItemDetails(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        Optional<TreasureItem> item = treasureItemService.getItemById(id);
        if (item.isPresent()) {
            response.put("success", true);
            response.put("item", item.get());
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "项目不存在");
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 批量删除项目
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/admin/treasure/batch-delete")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> batchDeleteItems(@RequestBody List<Long> itemIds) {
        Map<String, Object> response = new HashMap<>();
        try {
            for (Long id : itemIds) {
                treasureItemService.deleteItem(id);
            }
            response.put("success", true);
            response.put("message", "批量删除成功，共删除 " + itemIds.size() + " 个项目");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "批量删除失败：" + e.getMessage());
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 获取统计信息
     */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin/treasure/stats")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalCount", treasureItemService.getTotalCount());
        stats.put("websiteCount", treasureItemService.getCountByType(TreasureItem.ItemType.WEBSITE));
        stats.put("fileCount", treasureItemService.getCountByType(TreasureItem.ItemType.FILE));
        return ResponseEntity.ok(stats);
    }

    /**
     * 文件预览（后端流式返回，避免外部预览服务）
     */
    @GetMapping("/treasure/preview/{id}")
    @ResponseBody
    public ResponseEntity<StreamingResponseBody> previewFile(@PathVariable Long id) {
        Optional<TreasureItem> optionalItem = treasureItemService.getItemById(id);
        if (optionalItem.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        TreasureItem item = optionalItem.get();
        if (!Boolean.TRUE.equals(item.getEnabled()) || item.getType() != TreasureItem.ItemType.FILE || item.getFilePath() == null) {
            return ResponseEntity.badRequest().build();
        }

        String fileName = item.getOriginalFileName() != null ? item.getOriginalFileName() : "file";
        String contentType = item.getMimeType() != null ? item.getMimeType() : ossService.detectContentTypeByFilename(fileName);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(contentType));
        headers.setContentDisposition(ContentDisposition.inline().filename(fileName).build());

        StreamingResponseBody body = outputStream -> {
            try {
                ossService.streamFileTo(item.getFilePath(), outputStream);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        };
        return ResponseEntity.ok().headers(headers).body(body);
    }

    /**
     * 文件下载（后端流式返回，确保下载只发生在显式点击）
     */
    @GetMapping("/treasure/download/{id}")
    @ResponseBody
    public ResponseEntity<StreamingResponseBody> downloadFile(@PathVariable Long id) {
        Optional<TreasureItem> optionalItem = treasureItemService.getItemById(id);
        if (optionalItem.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        TreasureItem item = optionalItem.get();
        if (!Boolean.TRUE.equals(item.getEnabled()) || item.getType() != TreasureItem.ItemType.FILE || item.getFilePath() == null) {
            return ResponseEntity.badRequest().build();
        }

        String fileName = item.getOriginalFileName() != null ? item.getOriginalFileName() : "file";
        String contentType = item.getMimeType() != null ? item.getMimeType() : ossService.detectContentTypeByFilename(fileName);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(contentType));
        headers.setContentDisposition(ContentDisposition.attachment().filename(fileName).build());

        StreamingResponseBody body = outputStream -> {
            try {
                ossService.streamFileTo(item.getFilePath(), outputStream);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        };
        return ResponseEntity.ok().headers(headers).body(body);
    }
}